package com.example.demo.service;


import com.example.demo.dao.UserRepository;
import com.example.demo.domain.security.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import org.springframework.cache.annotation.Cacheable;

import java.util.List;
import java.util.Optional;

@Service
public class UserService {

    @Autowired
    UserRepository userRepository;

    //将查询结果添加到user的cache中，以name作为key
    @Cacheable(cacheNames = "user",key = "#name",condition = "#name != null")
    public User getUser(String name){
        Optional<User> u = userRepository.findById(name);
        return u.isEmpty()?null:u.get();
    }

    //移除cache中key为userName的对象
    @CacheEvict(cacheNames =  "user",key = "#userName")
    public void deleteUser(String userName){
        userRepository.deleteById(userName);
    }

    @CacheEvict(cacheNames = "user",key = "#name")
    public User updateUser(String name,User user){
        if(name == null || !name.equals(user.getName())|| userRepository.findById(name).isEmpty()){
            throw new RuntimeException("update error");
        }
        return userRepository.saveAndFlush(user);
    }

    public List<User> findAll(){
        return userRepository.findAll();
    }

    public User addUser(User user){
        return userRepository.save(user);
    }

}
